const Index = {
	isOpen : null,
	open(option){
		const opt = {
			url: '192.168.110.197:7272',
			param:{},
			...option
		}
		
		const socket = new WebSocket(`ws://${opt.url}`)
		
		this.socket = socket
		
		// 连接成功后执行
		socket.addEventListener('open', e => {
			console.log('Socket 连接成功')
			if($fn.hasObject( opt.param )){
				socket.send(JSON.stringify(opt.param));
			}
			opt.success && opt.success()
			this.isOpen = true
		})
		
		// 监听服务器推送的消息
		socket.addEventListener('message', e =>  {
			let { data } = e
			data = JSON.parse(data)
			console.log('收到服务器内容：', data);
			const { code, msg } = data
			opt.msg && opt.msg(data)
		})
		
		// 监听报错
		socket.addEventListener('error', e => {
			console.error('Socket 连接出错', e.data)
		})
		
		// 监听关闭
		socket.addEventListener('close', e => {
			console.error('Socket 已关闭', e.data)
		})
		
		return socket
	},
	send( data ){
		this.socket.send( JSON.stringify(data) )
	}
}

export default Index